import {
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common'
import { Logger } from 'src/utils/log4js'
import { BaseExceptionFilter } from '@nestjs/core'
import * as dayjs from 'dayjs'

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
  catch(exception: string|any, host: ArgumentsHost):void {
    const ctx = host.switchToHttp()
    const res = ctx.getResponse()
    const req = ctx.getRequest()

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR
    
        const code = status
        const logFormat = ` >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Request original url: ${req.originalUrl}
    Method: ${req.method}
    IP: ${req.ip}
    Status code: ${code}
    Params: ${JSON.stringify(req.params)}
    Query: ${JSON.stringify(req.query)}
    Body: ${JSON.stringify(
      req.body,
    )} \n  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  `
  console.log(logFormat)
    if (code >= 500) {
      Logger.error(logFormat)
    } else if (code >= 400) {
      Logger.warn(logFormat)
    } else {
      Logger.access(logFormat)
      Logger.info(logFormat)
    }
    res.status(status).json(
      Object.assign(
        {
          statusCode: status,
          timestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          path: req.url,
          message: exception.message
        },
      ),
    )
  }
}
